package com.viphuli.app.tool.adapter;

import java.util.List;

import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.ButterKnife;

import com.loopj.android.http.RequestParams;
import com.offroader.utils.ViewUtils;
import com.viphuli.app.tool.R;
import com.viphuli.app.tool.bean.page.ContactBean;
import com.viphuli.app.tool.common.AccessTokenKeeper;
import com.viphuli.app.tool.common.MyApp;
import com.viphuli.app.tool.fragment.BaseProgressFragment;
import com.viphuli.app.tool.http.ApiRequest;

public class ContactAdapter extends BaseAdapter {
	private List<ContactBean> list;
	private BaseProgressFragment caller;
	private int circleId;

	public ContactAdapter(BaseProgressFragment caller,List<ContactBean> list,int circleId) {
		this.list = list;
		this.caller=caller;
		this.circleId=circleId;
	}

	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public Object getItem(int index) {
		return list.get(index);
	}

	@Override
	public long getItemId(int index) {
		return index;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		ViewHolder holder = null;

		if (convertView == null || convertView.getTag() == null) {
			convertView = ViewUtils.inflateView(MyApp.getInstance(),
					R.layout.frag_contact_item);
			holder = new ViewHolder(convertView);
			convertView.setTag(holder);

		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		final ContactBean contactInfo = list.get(position);
		if (contactInfo != null) {
			holder.name.setText(contactInfo.getRealName());
			holder.tel.setText(contactInfo.getPhone());
			holder.submit.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					addManual(contactInfo.getRealName(),contactInfo.getPhone());
				}
			});
		}

		return convertView;
	}
	public void addManual(String name,String tel) {

		AccessTokenKeeper tokenKeeper = AccessTokenKeeper.readAccessToken(caller.getActivity());

		if (tokenKeeper.isLogin()) {

			RequestParams params = new RequestParams();
			params.put("user_name", name);
			params.put("phone_number", tel);
			params.put("uid", tokenKeeper.getOpenId());
			params.put("circle_id", circleId);
			ApiRequest.circleUserAddManual.request(caller, params);

		}

	}
	protected class ViewHolder {

		@Bind(R.id.id_contact_item_name)
		TextView name;

		@Bind(R.id.id_contact_item_submit)
		TextView submit;

		@Bind(R.id.id_contact_item_tel)
		TextView tel;

		public ViewHolder(View view) {
			ButterKnife.bind(this, view);
		}
	}
}
